using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

namespace LS.UnityExtensions.Editor
{
    public abstract class ProjectSettingProvider<TProvider,TSetting> : SettingsProvider 
        where TProvider : ProjectSettingProvider<TProvider,TSetting>, new()
        where TSetting : ProjectSettingScriptableObject<TSetting>
    {
        SerializedObject settingsWrapper;
        UnityEditor.Editor cachedEditor;
        public static ProjectSettingProvider<TProvider,TSetting> Instance { get; protected set; }

        protected abstract TSetting GetSetting();
        
        public ProjectSettingProvider(string path, IEnumerable<string> keywords = null) : base(path, SettingsScope.Project, keywords)
        {
            
        }
        
        public override void OnGUI(string searchContext)
        {
            if (settingsWrapper == null || settingsWrapper.targetObject == null)
            {
                TSetting settings = GetSetting();
                InitEditorData(settings);
            }

            if (settingsWrapper != null && settingsWrapper.targetObject != null && cachedEditor != null)
            {
                settingsWrapper.Update();
                cachedEditor.OnInspectorGUI();
                settingsWrapper.ApplyModifiedProperties();
            }
        }

        public override void OnActivate(string searchContext, VisualElement rootElement)
        {
            TSetting setting = GetSetting();
            InitEditorData(setting);
        }

        public override void OnDeactivate()
        {
            cachedEditor = null;
            settingsWrapper = null;
            GetSetting()?.Save();
        }

        private void InitEditorData(ScriptableObject settings)
        {
            if (!settings) { return; }
            settingsWrapper = new SerializedObject(settings);
            UnityEditor.Editor.CreateCachedEditor(settings, null, ref cachedEditor);
        }
    }
}
